from flask import Flask, render_template, request, jsonify, g
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from elevatorControl import ElevatorSystem
from mqttControl import MQTTClient
import uuid
import time

# 初始化Flask应用
app = Flask(__name__, 
            static_url_path='/data',  # URL 中静态文件的路径前缀
            static_folder='../static',
            template_folder="../templates")     # 静态文件所在的文件夹路径
app.config['SECRET_KEY'] = 'your-secret-key-here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///orders.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

def custom_message_handler(topic: str, payload: str):
    """自定义消息处理函数"""
    print(f"自定义处理 - 主题: {topic}, 内容: {payload}")
    # 模拟耗时处理
    time.sleep(2)
    print(f"完成对消息 '{payload[:20]}...' 的处理")

# 创建线程化的MQTT客户端实例
mqtt_client = MQTTClient(
    client_id=f"mqtt-client-{int(time.time())}",
    broker_host='localhost',
    broker_port=1883
)

# 设置自定义消息处理函数
mqtt_client.set_message_callback(custom_message_handler)

if mqtt_client.connect():
    print("MQTT客户端已在后台线程启动")
    # 订阅测试主题
    mqtt_client.subscribe('robot/task_manager', qos=1)
VIN = "master00001"

# 初始化数据库
db = SQLAlchemy(app)

# 订单模型
class Order(db.Model):
    id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    table_number = db.Column(db.String(20), nullable=False)
    total_amount = db.Column(db.Float, nullable=False)
    status = db.Column(db.String(20), default='pending')  # pending, completed, cancelled
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    # 关系：一个订单包含多个订单项
    items = db.relationship('OrderItem', backref='order', lazy=True, cascade="all, delete-orphan")


# 订单项模型
class OrderItem(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    order_id = db.Column(db.String(36), db.ForeignKey('order.id'), nullable=False)
    food_id = db.Column(db.String(20), nullable=False)
    food_name = db.Column(db.String(100), nullable=False)
    quantity = db.Column(db.Integer, nullable=False)
    price = db.Column(db.Float, nullable=False)


# 菜品数据（实际应用中可以从数据库加载）
menu_items = [
    {"id": "1", "name": "汉堡", "price": 38, "image": "/data/images/menu_1.png", "rating": 4.8,
     "tag": "热销"},
    {"id": "2", "name": "薯条", "price": 28, "image": "/data/images/menu_2.png", "rating": 4.6,
     "tag": ""},
    {"id": "3", "name": "橙汁", "price": 22, "image": "/data/images/menu_3.png", "rating": 4.5,
     "tag": "热销"},
    {"id": "4", "name": "可乐", "price": 32, "image": "/data/images/menu_4.png", "rating": 4.9,
     "tag": "热销"},
    {"id": "5", "name": "毛巾", "price": 18, "image": "/data/images/menu_5.png", "rating": 4.7,
     "tag": ""},
    {"id": "6", "name": "牙刷", "price": 128, "image": "/data/images/menu_6.png",
     "rating": 4.9, "tag": "特惠"},
]

# 分类数据
categories = ["全部", "热门推荐", "招牌主食", "特色小菜", "美味汤品", "甜点饮品", "套餐组合"]

# 创建数据库表
with app.app_context():
    db.create_all()

# 初始化电梯系统
elevator_system = ElevatorSystem(num_elevators=1)

# 电梯控制界面
@app.route('/elevator')
def index():
    """后台管理界面"""
    return render_template('elevator.html')

# 获取电梯状态
@app.route('/api/status')
def get_status():
    """获取所有电梯状态的API"""
    # print(elevator_system.get_all_statuses())
    return jsonify(elevator_system.get_all_statuses())

@app.route('/api/request', methods=['POST'])
def add_request():
    """添加电梯请求的API"""
    data = request.json
    floor = data.get('floor')
    direction = data.get('direction')

    if floor is None:
        return jsonify({"error": "缺少楼层参数"}), 400
    try:
        floor = int(floor)
        elevator_system.add_request(floor, direction)
        return jsonify({"success": True})
    except ValueError:
        return jsonify({"error": "楼层必须是整数"}), 400
    
@app.route('/api/elevator/<int:elevator_id>/target', methods=['POST'])
def add_elevator_target(elevator_id):
    """为指定电梯添加目标楼层"""
    data = request.json                "coordinatePoint":[
                {
                    "x": 1.0,
                    "y": 1.0,
                    "theta": 1.0,
                    "point_id":int(new_order.table_number)
                }
                ],
                "task_id": 231290841240
    floor = data.get('floor')
    if floor is None:
        return jsonify({"error": "缺少楼层参数"}), 400
    try:
        floor = int(floor)
        for elevator in elevator_system.elevators:
            if elevator.id == elevator_id:
                success = elevator.add_target(floor)
                return jsonify({"success": success})
        return jsonify({"error": "电梯不存在"}), 404
    except ValueError:
        return jsonify({"error": "楼层必须是整数"}), 400

# 点餐界面
@app.route('/ordering')
def index_order():
    return render_template('index.html', menu_items=menu_items, categories=categories)

# 提交订单API
@app.route('/api/submit-order', methods=['POST'])
def submit_order():
    data = request.get_json()
    print(data)
    # 验证数据
    if not data or not data.get('table_number') or not data.get('items'):
        return jsonify({"success": False, "message": "缺少必要的订单信息"}), 400
    try:
        # 创建新订单
        new_order = Order(
            table_number=data.get('table_number'),
            total_amount=data.get('total')
        )

        # 添加订单项
        for item in data.get('items'):
            order_item = OrderItem(
                food_id=item.get('id'),
                food_name=item.get('name'),
                quantity=item.get('quantity'),
                price=item.get('price')
            )
            new_order.items.append(order_item)
        # 保存到数据库
        db.session.add(new_order)
        db.session.commit()
        response = {
            "VIN": VIN,
            "terminal_id": 2,
            "frame_id": 933,
            "sys_data_type": 1004,
            "time_stamp": int(time.time()),
            "code": 10,
            "data": {
                "tasktype": 1,
                "coordinatePoint":[
                {
                    "x": 1.0,
                    "y": 1.0,
                    "theta": 1.0,
                    "point_id":int(new_order.table_number)
                }
                ],
                "task_id": 231290841240
            }
        }

        mqtt_client.publish("robot/task_manager", response, qos=1)

        return jsonify({
            "success": True,
            "message": "订单提交成功",
            "order_id": new_order.id
        })

    except Exception as e:
        db.session.rollback()
        return jsonify({"success": False, "message": f"提交订单失败: {str(e)}"}), 500


# 获取订单状态API
@app.route('/api/order-status/<order_id>')
def get_order_status(order_id):
    order = Order.query.get(order_id)
    if not order:
        return jsonify({"success": False, "message": "订单不存在"}), 404

    return jsonify({
        "success": True,
        "order_id": order.id,
        "status": order.status,
        "created_at": order.created_at.strftime('%Y-%m-%d %H:%M:%S')
    })


# 商家查看订单页面
@app.route('/orders')
def view_orders():
    orders = Order.query.order_by(Order.created_at.desc()).all()
    return render_template('orders.html', orders=orders)


# 更新订单状态
@app.route('/api/update-order/<order_id>', methods=['POST'])
def update_order(order_id):
    order = Order.query.get(order_id)
    if not order:
        return jsonify({"success": False, "message": "订单不存在"}), 404

    data = request.get_json()
    if 'status' in data:
        order.status = data['status']
        db.session.commit()
        return jsonify({"success": True, "message": "订单状态已更新"})

    return jsonify({"success": False, "message": "无效的请求"}), 400

if __name__ == '__main__':
    try:
        app.run(host='0.0.0.0',debug=True, threaded=True)
    finally:
        mqtt_client.disconnect()
        elevator_system.stop()

